//
//  XBaseViewController.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/8.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit

/// 项目中的控制器基类
class XBaseController: UIViewController {
    /// 是否上拉刷新
    var isPullUp:Bool = false
    //自定义导航栏
    lazy var navBar:UINavigationBar = UINavigationBar(frame:CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    //自定义导航栏的item，通过设置item来设置导航栏
    lazy var navBarItem:UINavigationItem = UINavigationItem()
    //访客视图字典,传给visitorView
    var visitorInfo:[String:String]?
    var myTableView:UITableView?
    lazy var visitorView:XVisitorView = XVisitorView()
    /// 刷新控件
    lazy var tableReFreshCtr:UIRefreshControl = UIRefreshControl()
    ///登录标记
//    var isLogin:Bool = false
    
    override var title: String?{
        didSet{
            navBarItem.title = title
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        XNetworkManager.shared.userAccount.access_token != nil ? loadData() : ()
        //注册登录成功的通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name.init(XUserLoginSuccessedNotification), object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    /// 加载更多
    func loadMore(){
        
    }
    /// 下拉刷新
    func loadData(){
        tableReFreshCtr.endRefreshing()
    }
    
    
}
fileprivate extension XBaseController{
    @objc func loginSuccess(){
        print(#function)
        // 更新 UI => 将访客视图替换为表格视图
        // 需要重新设置 view
        // 在访问 view 的 getter 时，如果 view == nil 会调用 loadView -> viewDidLoad
        view = nil
        //清除导航上的登录注册按钮
        navBarItem.leftBarButtonItem = nil
        navBarItem.rightBarButtonItem = nil
        // 注销通知 -> 重新执行 viewDidLoad 会再次注册！避免通知被重复注册
        NotificationCenter.default.removeObserver(self)
        
    }
    
   
    
}
// MARK: - UI相关
fileprivate extension XBaseController{
    /// UI初始化
    func setupUI(){
        view.backgroundColor = UIColor.white
        automaticallyAdjustsScrollViewInsets = false
        setupNav()
        //如果已经登录就显示表格，否则显示访客视图
        XNetworkManager.shared.userAccount.access_token != nil ? setupTableView():setupVisitorView()
    }
    ///初始化导航栏
    func setupNav(){
        
        navBar.items = [navBarItem]
        //整个bar的渲染
        navBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        navBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        //设置bar上的文字颜色
        navBar.tintColor = UIColor.orange
        view.addSubview(navBar)
    }
    
    /// 初始化列表
    func setupTableView(){
//        print(#function)
        myTableView = UITableView(frame: view.bounds, style: .plain)
        myTableView?.delegate = self
        myTableView?.dataSource = self
        myTableView?.addSubview(tableReFreshCtr)
        tableReFreshCtr.addTarget(self, action: #selector(loadData), for: .valueChanged)
        automaticallyAdjustsScrollViewInsets = false
        view.insertSubview(myTableView!, belowSubview: navBar)
        myTableView?.contentInset = UIEdgeInsets(top: navBar.bounds.height,
                                                 left: 0,
                                                 bottom: tabBarController?.tabBar.bounds.height ?? 0,
                                                 right: 0)
        
        // 修改指示器的缩进 - 强行解包是为了拿到一个必有的 inset
        myTableView?.scrollIndicatorInsets = UIEdgeInsets(top: navBar.bounds.height,
                                                          left: 0,
                                                          bottom: tabBarController?.tabBar.bounds.height ?? 0,
                                                          right: 0)
    }
    /// 访客视图
    func setupVisitorView(){
        print(#function)
        visitorView = XVisitorView(frame: view.bounds)
        visitorView.visitorInfo = visitorInfo
        visitorView.loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registBtn.addTarget(self, action: #selector(regist), for: .touchUpInside)
        
        navBarItem.leftBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: #selector(regist))
        navBarItem.rightBarButtonItem = UIBarButtonItem(title: "登录", target: self, action: #selector(login))
        view.insertSubview(visitorView, belowSubview: navBar)
    }
    @objc func login() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: XUserShouldLoginNotification), object: nil)
        print(#function)
    }
    @objc func regist(){
        print(#function)
    }
}
//tableView的代理及数据源方法实现
extension XBaseController:UITableViewDelegate,UITableViewDataSource{
    
    //MARK: TableView DATA SOURCE
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        return UITableViewCell()
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //行
        let row = indexPath.row
        //        print(" will show row == \(row)")
        //分组
        let se = indexPath.section
        //分组数
        let section = tableView.numberOfSections - 1
        if row < 0 || se < section{
            //            if row < 0 || section<0{
            return
        }
        //如果是最后一个分组了
        let count = tableView.numberOfRows(inSection: section)
        ///
        let refrechRow = count-1
        if(row == refrechRow && !isPullUp){
            print("到\(refrechRow)了，准备上拉刷新了")
            
            isPullUp = true
            loadMore()
        }
        
    }
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 60
//    }
    
}
